// 初始化地图
let map = new BMapGL.Map("allmap", {
    enableTilt: false
});
map.enableScrollWheelZoom();
var scaleCtrl = new BMapGL.ScaleControl();  // 添加比例尺控件
map.addControl(scaleCtrl);
var navigationCtrl = new BMapGL.NavigationControl3D();  // 添加指南针控件
map.addControl(navigationCtrl);
map.centerAndZoom(new BMapGL.Point(103.99312122710032, 30.769698697175492), 14);

// 聊天功能相关
let chatHistory = [];

function addMessage(content, role) {
    const container = document.getElementById('messages-container');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}-message`;
    messageDiv.innerHTML = `
        <div class="message-content">${content}</div>
        <div class="message-meta" style="font-size: 12px; color: #666; margin-top: 5px;">
            ${new Date().toLocaleTimeString()}
        </div>
    `;
    container.appendChild(messageDiv);
    container.scrollTop = container.scrollHeight;
}

function addLoadingIndicator() {
    const container = document.getElementById('messages-container');
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'loading-indicator';
    loadingDiv.id = 'loading-' + Date.now();
    loadingDiv.textContent = '正在生成回答...';
    container.appendChild(loadingDiv);
    container.scrollTop = container.scrollHeight;
    return loadingDiv.id;
}

function removeLoadingIndicator(id) {
    const element = document.getElementById(id);
    if (element) element.remove();
}

// 表单提交处理
document.getElementById('input-form').addEventListener('submit', async function (e) {
    e.preventDefault();
    const textarea = document.getElementById('input-text');
    const userInput = textarea.value.trim();
    if (!userInput) return;

    textarea.disabled = true;
    e.submitter.disabled = true;

    try {
        addMessage(userInput, 'user');
        textarea.value = '';
        const loadingId = addLoadingIndicator();

        const response = await fetch('/LLMTourMapGenApp/get_script/', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                text: userInput,
                history: chatHistory.map(msg => ({
                    role: msg.role,
                    content: msg.content
                }))
            })
        });

        const data = await response.json();
        removeLoadingIndicator(loadingId);
        addMessage(data.advice, 'ai');
        chatHistory.push({ role: 'user', content: userInput });
        chatHistory.push({ role: 'ai', content: data.advice });

        document.getElementById('export-btn').disabled = false;

        if (data.getRoutePath === true) {
            getRoutePath(data, map);
        }
        else if (data.searchPlace === true) {
            searchPlace(data, map);
        }
        else {
            map.setMapStyleV2({ styleJson: data.styleJson });
        }
    } catch (error) {
        console.error('Error:', error);
        addMessage('请求失败，请稍后重试', 'ai');
    } finally {
        textarea.disabled = false;
        e.submitter.disabled = false;
    }
});

// 添加导出按钮点击处理
document.getElementById('export-btn').addEventListener('click', async () => {
    try {
        const response = await fetch('/LLMTourMapGenApp/export/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken'),
            },
            credentials: 'same-origin'
        });

        const data = await response.json();
        if (data.url) {
            window.open(data.url, '_blank');
        } else {
            alert('导出失败：' + (data.error || '未知错误'));
        }
    } catch (error) {
        console.error('导出错误:', error);
    }
});

// CSRF令牌获取函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.startsWith(name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}